package myJs.missionManage

import japgolly.scalajs.react.React.Fragment
import japgolly.scalajs.react.ScalaFnComponent
import japgolly.scalajs.react.callback.Callback
import japgolly.scalajs.react.vdom.all._
import myJs.PredictResult
import myJs.Utils._
import myJs.api.Api
import myJs.cps.BootstrapTableCp._
import myJs.myPkg.Hooks._
import myJs.myPkg._
import myJs.myPkg.jquery.$
import org.scalajs.dom.window
import myJs.Implicits._
import myJs.cps.BootstrapTableCp
import myJs.tool.Pojo._
import myJs.tool.Tool
import shared.pojo.App._

import scala.collection.immutable.SeqMap

/** Created by yz on 10/10/2023
  */
object TableCp {

  val Component = ScalaFnComponent[Unit] { props =>

    val (datas, setDatas) = useState(List.empty[ujson.Obj])
    val (columns, setColumns) = useState(List.empty[Column])
    val (selectedIds, setSelectedIds) = useState(List[String]())

    object FTool {

      def refreshTableB = {
        Api.mission.all.flatMapSync { response =>
          setDatas(response)
        }
      }

      def tbFmt(field: String) = (v: ujson.Value, row: ujson.Obj) => {
        field match {
          case _ => Fragment(v.myStr)
        }
      }

      def comVFmt(fileTitle: String) = (v: ujson.Value, row: ujson.Obj) => {
        fileTitle match {
          case _ => v.myStr
        }
      }

      def operateFmt = (v: ujson.Value, row: ujson.Obj) => {
        span(
          a(
            onClick --> Callback { PredictResult.showResult(row("id").myStr) },
            title := "查看结果",
            cursor.pointer,
            span(em(className := "fa fa-eye"))
          ),
          " ",
          a(
            onClick --> FTool.delete(row("id").myStr),
            title := "删除",
            cursor.pointer,
            span(em(className := "fa fa-close"))
          ),
          " "
        )
      }

      def getColumns(infoMap: SeqMap[String, String]): List[Column] = {
        val map = infoMap
        val basicColumns = map.map { case (k, v) =>
          val searchKind = k match {
            case "age" | "ast" | "alt" | "plt" | "score" => NumericSearch
            case "result" => CheckboxSearch
            case _ => TextSearch
          }
          val operable = k match {
            case _ => true
          }
          val fmt = FTool.tbFmt(k)
          val comVF = FTool.comVFmt(v)
          val optionMap = k match {
            case "result" => List("低慢性肝病风险", "早期肝纤维化风险", "晚期肝纤维化风险", "肝硬化风险").optionMap
            case _ => SeqMap[String, String]()
          }
          Column(
            field = k,
            title = v,
            operable = operable,
            searchKind = searchKind,
            formatter = fmt,
            comVF = comVF,
            optionMap = optionMap
          )
        }.toList
        val checkColumn = Column(field = "state", checkbox = true, comVF = FTool.comVFmt(""))
        val operateColumn =
          Column(field = "operate", title = "操作", formatter = FTool.operateFmt, comVF = FTool.comVFmt(""))
        (checkColumn :: basicColumns) :+ operateColumn
      }

      def delete(missionId: String) = Callback {
        val options = SwalOptions(
          title = "",
          text = "确定要删除此记录吗？",
          `type` = "warning",
          showCancelButton = true,
          showConfirmButton = true,
          confirmButtonClass = Tool.confirmButtonClass,
          confirmButtonText = "确定",
          closeOnConfirm = false,
          cancelButtonText = "取消",
          showLoaderOnConfirm = true,
          cancelButtonClass = Tool.cancelButtonClass
        )
        swal(
          options, {
            Api.mission.deletes(IdsData(ids = List(missionId.toInt))).flatMap { x =>
              FTool.refreshTableB.map { x =>
                swal(SwalOptions(title = "成功", text = "删除成功", `type` = "success"))
              }
            }
          }
        )
      }

      def exportPdf = {
        val index = layer.alert(element, layerOptions)
        Api.mission.all(IdsData(ids = selectedIds.map(_.toInt))).flatMap { response =>
          $("#svgs").empty()
          val svgStrs = response.zipWithIndex.map { case (missionInfo, curI) =>
            $("#svgs").append(s"<div id='svgs${curI}'></div>")
            PredictResult.refreshSvg(missionInfo.score.toDouble, 2, s"svgs${curI}")
            $(s"#svgs${curI}").html()
          }
          Api.predict.exportPdfs(ExportPdfData(missionIds = response.map(_.id), svgStrs = svgStrs)).flatMapSync {
            response =>
              window.location.href = s"${Api.predict.baseUrl}/exportPdfByDir?dir=${response.dir.encodeURI}"
              layer.close(index)
              setSelectedIds(List.empty)
          }
        }

      }

      def deleteAllInfos = Callback {
        val options = SwalOptions(
          title = "",
          text = "确定要删除选中的记录吗？",
          `type` = "warning",
          showCancelButton = true,
          showConfirmButton = true,
          confirmButtonClass = Tool.confirmButtonClass,
          confirmButtonText = "确定",
          closeOnConfirm = false,
          cancelButtonText = "取消",
          showLoaderOnConfirm = true,
          cancelButtonClass = Tool.cancelButtonClass
        )
        swal(
          options, {
            Api.mission.deletes(IdsData(ids = selectedIds.map(_.toInt))).flatMap { x =>
              FTool.refreshTableB.map { x =>
                swal(SwalOptions(title = "成功", text = "删除记录成功!", `type` = "success"))
              }
            }
          }
        )
      }
    }

    useEffect(
      {
        val map =
          SeqMap(
            "sampleId" -> "样品号",
            "name" -> "姓名",
            "age" -> "年龄",
            "ast" -> "AST",
            "alt" -> "ALT",
            "plt" -> "PLT",
            "score" -> "风险得分",
            "result" -> "结果",
            "unit" -> "送检单位",
            "address" -> "地址",
            "sex" -> "性别",
            "office" -> "送检科室",
            "doctor" -> "申请医生",
            "number" -> "门诊/住院号",
            "sampleTime" -> "采样时间",
            "submitTime" -> "送检时间",
            "sampleType" -> "样本类型",
            "sampleStatus" -> "样本状态",
            "title" -> "标题",
            "reporter" -> "检验人",
            "checker" -> "审核人",
            "checkDate" -> "检验日期",
            "reportDate" -> "报告日期"
          )
        val curColumns = FTool.getColumns(map)
        setColumns(curColumns) >>
          FTool.refreshTableB.toCallback
      },
      List()
    )

    val deletesDisabled = selectedIds.isEmpty

    div(
      div(
        id := "",
        button(
          className := "btn btn-primary",
          disabled := deletesDisabled,
          onClick --> FTool.deleteAllInfos,
          i(className := "glyphicon glyphicon-trash"),
          " 删除选中记录"
        ),
        " ",
        button(
          className := "btn btn-primary",
          disabled := deletesDisabled,
          onClick --> FTool.exportPdf,
          i(className := "glyphicon glyphicon-export"),
          " 批量导出Pdf报告"
        )
      ),
      BootstrapTableCp
        .Props(
          columns = columns,
          datas = datas,
          selectColumnEnabled = true,
          extraFixedColumns = List("sampleId", "age", "ast", "alt", "plt", "score", "result"),
          showColumnNames = List("样品号", "年龄", "AST", "ALT", "PLT", "风险得分", "结果", "检验日期"),
          selectedIds = selectedIds,
          selectedIdsChange = setSelectedIds.toCallback,
          search = true
        )
        .render
    )

  }

}
